package kr.co.doriclassic.chapter23;

public class ThreadControl {
	static void print(String msg) {
		String threadName = Thread.currentThread().getName();
		System.out.format("%s: %s%n", threadName, msg);
	}
	
	private static class MessageLoop implements Runnable{
	
		@Override
		public void run() {
			String[] message = {
					"Pride will have a fail.",
					"Power is dangerous unless you have humility.",
					"Office changes manners.",
					"Empty vessels make the most sound."
			};
			for (int i = 0; i < message.length; i++) {
				
				try {
					print(message[i]);
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					print("아직 끝나지 않았어요.");
				}
			}
		}//run	
	}//MessageLoop
	
	public static void main(String[] args) throws InterruptedException {
		int tries = 0;//시도횟수
		print("추가적인 쓰레드를 시작합니다.");
		Thread t = new Thread(new MessageLoop());
		t.start();
		
		print("추가적인 쓰레드가 끝나기를 기다립니다.");
		
		while(t.isAlive()){
			print("아직 기다립니다.");
			t.join(1000);
			tries++;
			if(tries>2){
				print("참을 수 없네요.");
				t.interrupt();
				t.join();
			}
		}
		print("메인 쓰레드 종료.");
	}
}
